import React, {Component} from 'react';
import {
    StyleSheet,
    Text,
    View,
    Image,
    Dimensions,
    ListView,
    TouchableOpacity,
    TextInput,
    AsyncStorage,
    DeviceEventEmitter,
    Platform,
    StatusBar
} from 'react-native';

const {height, width} = Dimensions.get('window');
import Config from '../../common/Config'
import Utils from '../../common/Utils'
import {Toast,ModalIndicator} from 'teaset';
const STORAGE_KEY_TOKEN = '@AsyncStorageDemo:key_token';
export default class ModifyPage extends Component {
    componentDidMount() {
        this._loadInitialState().done();
    }
    async _loadInitialState(){
        try{
            let value=await AsyncStorage.getItem(STORAGE_KEY_TOKEN);
            if(value!==null){
                this._appendMessage(value);
            }else{
                this._appendMessage('');
            }
        }catch(error){
            this._appendMessage('AsyncStorage错误'+error.message);
        }
    }
    _appendMessage=(message)=>{
        this.setState({
            token:this.state.token.concat(message)
        },()=>this.getInfo());
    };
    constructor(props) {
        super(props);
        this.state = {
            nickname:'阿飞',
            token:''
        }
    };

    getInfo=()=>{
        let params={
            "token":this.state.token,
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/user/getInfo',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status!==1){
                    this.setState({
                        nickname:responseJson.data.nickname
                    })
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };

    modify=()=>{
        this.nicknameTextInput.blur();
        let params={
            "token":this.state.token,
            "newNickname":this.state.nickname
        };
        ModalIndicator.show("正在请求数据......");
        fetch(Config.baseApi+'/user/modifyNickname',{
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: Utils.getParamsString(params)
        })
            .then((response) => response.json())
            .then((responseJson) => {
                ModalIndicator.hide();
                if(responseJson.status!==1){
                    Toast.message('修改成功');
                    Actions.pop();
                    DeviceEventEmitter.emit('refreshing','sss')
                }else{
                    Toast.message(responseJson.msg);
                }
            })
            .catch((error) => {
                ModalIndicator.hide();
                Toast.message(error);
            });
    };

    render() {
        return (
            <View style={styles.container}>
                <StatusBar  backgroundColor="white"
                            barStyle="dark-content"/>
                <View style={styles.titleView}>
                    <TouchableOpacity
                        onPress={()=>Actions.pop()}
                        style={styles.goBackView}>
                        <Text style={styles.goBackMsg}>取消</Text>
                    </TouchableOpacity>
                    <Text style={styles.titleMsg}>修改昵称</Text>
                    <TouchableOpacity
                        onPress={()=>this.modify()}
                        style={styles.completeView}>
                        <Text style={styles.completeMsg}>完成</Text>
                    </TouchableOpacity>
                </View>
                <View style={{height:10}}/>
                <View style={styles.labelView}>
                    <TextInput ref={ (ref)=>this.nicknameTextInput = ref }
                               autoCapitalize={"none"}
                               underlineColorAndroid={'transparent'}
                               defaultValue={this.state.nickname}
                               autoCorrect={false}
                               style={styles.textInputView}
                               onChangeText={(text)=>{
                                   this.setState({
                                       nickname:text,
                                   })
                               }}/>
                </View>
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor:'#f0f0f0'
    },
    titleView:{
        backgroundColor:'#ffffff',
        width:width,
        alignItems:'center',
        justifyContent:'center',
        height:Platform.OS==='ios'?64:44
    },
    titleMsg:{
        fontSize:17,
        color:'#000000',
        marginTop:Platform.OS==='ios'?34:14,
        marginBottom:29/2
    },
    goBackView:{
        position: 'absolute',
        top:Platform.OS==='ios'?65/2:10,left:15,
    },
    goBackMsg:{
        color:'#000000',
        fontSize:17
    },
    completeView:{
        position: 'absolute',
        right:15,top:Platform.OS==='ios'?65/2:10
    },
    completeMsg:{
        color:'#3090dd',
        fontSize:17
    },
    labelView:{
        height:45,
        width:width,
        backgroundColor:'#ffffff'
    },
    textInputView:{
        height:45,
        marginLeft:15,
        width:width-15
    }
});
